import React, { Component } from 'react'
import { Dimensions, StyleSheet, Text, View } from 'react-native'
import { inject, observer } from 'mobx-react/native'
import { withNavigation } from 'react-navigation'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'

import { List, Picker, SegmentedControl } from 'antd-mobile'
import { Events, IconButton } from '../components'
import { variables } from '../styles'

/**
 * @typedef {'' | 'self' | Role} EventsFilter
 * @param {EventsFilter} navigation.state.params.filter
 */
@inject('actions', 'store')
@observer
export class EventsScreen extends Component {
  static navigationOptions = ({ navigation }) => ({
    headerLeft: <View />,
    headerRight: (
      <IconButton name="add" onPress={() => navigation.navigate('Event')} />
    ),
    headerTitle: (
      <SegmentedControl
        style={{ width: Dimensions.get('window').width / 2 }}
        values={['All', 'Yours']}
        selectedIndex={navigation.getParam('filter') !== 'self' ? 0 : 1}
        onChange={({ nativeEvent: { selectedSegmentIndex: index } }) =>
          navigation.setParams({ filter: ['', 'self'][index] })
        }
      />
    ),
    headerTitleStyle: { alignSelf: 'center' },
  })

  render = () => (
    <View style={styles.container}>
      {this.props.navigation.getParam('filter') === 'self' ? (
        <EventsByUser id={this.props.store.user.id} />
      ) : (
        <EventsByRole
          filter={this.props.navigation.getParam('filter', '')}
          onChangeFilter={filter => this.props.navigation.setParams({ filter })}
        />
      )}
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
})

@graphql(
  gql`
    query($roles: [Role!]) {
      allEvents(
        filter: { from: { role_in: $roles } }
        orderBy: updatedAt_DESC
      ) {
        id
        from {
          id
          username
          name
          role
        }
        content
        createdAt
        updatedAt
      }
    }
  `,
  {
    options: ({ filter }) => ({
      variables: {
        roles: filter ? [filter] : ['CUSTOMER', 'MANAGER', 'ADMINISTRATOR'],
      },
    }),
  },
)
class EventsByRole extends Component {
  render = () => (
    <View style={{ flex: 1 }}>
      <Picker
        data={[
          { label: 'All', value: '' },
          { label: 'Customer', value: 'CUSTOMER' },
          { label: 'Manager', value: 'MANAGER' },
          { label: 'Administrator', value: 'ADMINISTRATOR' },
        ]}
        cols={1}
        okText="Ok"
        dismissText="Cancel"
        value={[this.props.filter || '']}
        onOk={value => this.props.onChangeFilter(value[0])}
      >
        <List.Item arrow="horizontal">
          <Text
            style={{
              color: variables.color_text_caption,
              fontSize: variables.font_size_heading,
            }}
          >
            Filter
          </Text>
        </List.Item>
      </Picker>

      <Events
        data={this.props.data.loading ? [] : this.props.data.allEvents}
        loading={this.props.data.loading}
        onRefresh={this.props.data.refetch}
      />
    </View>
  )
}

@graphql(
  gql`
    query($id: ID!) {
      allEvents(filter: { from: { id: $id } }, orderBy: updatedAt_DESC) {
        id
        from {
          id
          username
          name
          role
        }
        content
        createdAt
        updatedAt
      }
    }
  `,
  { options: ({ id, store }) => ({ variables: { id } }) },
)
class EventsByUser extends Component {
  render = () => (
    <View style={{ flex: 1 }}>
      <Events
        data={this.props.data.loading ? [] : this.props.data.allEvents}
        loading={this.props.data.loading}
        onRefresh={this.props.data.refetch}
      />
    </View>
  )
}
